package com.ruoyi.learn.java.design.pattern.behavior;

// 文件名：MediatorInOneClass.java

import java.util.ArrayList;
import java.util.List;

/**
 * 演示如何在一个Java类文件中实现中介者模式
 */
public class MediatorInOneClass {

    // ==================== 抽象中介者接口 ====================
    public interface ChatMediator {
        void sendMessage(String message, User user);
        void addUser(User user);
    }

    // ==================== 抽象同事类 ====================
    public abstract static class User { // 注意：如果外部类不是 static，内部类需要声明为 static
        protected String name;
        protected ChatMediator mediator;

        public User(ChatMediator mediator, String name) {
            this.mediator = mediator;
            this.name = name;
        }

        public abstract void send(String message);
        public abstract void receive(String message);
    }

    // ==================== 具体中介者 ====================
    public static class ChatRoom implements ChatMediator {
        private List<User> users;

        public ChatRoom() {
            this.users = new ArrayList<>();
        }

        @Override
        public void addUser(User user) {
            users.add(user);
        }

        @Override
        public void sendMessage(String message, User user) {
            for (User u : users) {
                if (u != user) { // 避免发送者收到自己的消息
                    u.receive(message);
                }
            }
        }
    }

    // ==================== 具体同事类 ====================
    public static class ChatUser extends User {
        public ChatUser(ChatMediator mediator, String name) {
            super(mediator, name);
            mediator.addUser(this); // 自动加入聊天室
        }

        @Override
        public void send(String message) {
            System.out.println(this.name + " 发送消息: " + message);
            mediator.sendMessage(message, this);
        }

        @Override
        public void receive(String message) {
            System.out.println(this.name + " 收到消息: " + message);
        }
    }

    // ==================== 主方法 (客户端) ====================
    public static void main(String[] args) {
        System.out.println("=== 中介者模式 - 单文件实现 ===\n");

        // 创建中介者（聊天室）
        ChatMediator chatRoom = new ChatRoom();

        // 创建用户（具体同事）
        User alice = new ChatUser(chatRoom, "Alice");
        User bob = new ChatUser(chatRoom, "Bob");
        User charlie = new ChatUser(chatRoom, "Charlie");

        // Alice 发送消息
        System.out.println("--- Alice 发送消息 ---");
        alice.send("大家好！");

        // Bob 发送消息
        System.out.println("\n--- Bob 发送消息 ---");
        bob.send("嗨，Alice！Charlie也在啊。");

        // Charlie 发送消息
        System.out.println("\n--- Charlie 发送消息 ---");
        charlie.send("你们好！");
    }
}